package chances.epg.ui.taglib.html;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

import org.apache.commons.lang.StringUtils;

import chances.epg.ui.taglib.EpgPageContextResolver;
import chances.epg.ui.taglib.model.EpgPageContext;
import chances.epg.ui.taglib.model.Widget;

@SuppressWarnings("serial")
public class WidgetTag extends EpgTagSupport {
	private String widget;
	private String options;

	@Override
	public int doEndTag() throws JspException {
		if (StringUtils.isNotEmpty(this.widget)) {
			Tag tag = this.getParent();
			if(EpgRectTag.class.isInstance(tag)){
				EpgRectTag epgRectTag = (EpgRectTag) tag;
				epgRectTag.setWidget(this.widget);
				if(this.options==null){
					this.options = this.getBodyContent().getString();
				}
				epgRectTag.setOptions(this.options);
				epgPageContext.addWidget(this.createWidget(epgRectTag.getId()));
			}
		}
		this.widget = null;
		this.options = null;

		return super.doStartTag();
	}

	public Widget createWidget(String id) {
		Widget aWidget = new Widget();
		aWidget.setType(this.widget);
		aWidget.setId(id);
		aWidget.setOptions(this.options);
		return aWidget;
	}

	public String getWidget() {
		return widget;
	}

	public String getOptions() {
		return options;
	}

	public void setWidget(String widget) {
		this.widget = widget;
	}

	public void setOptions(String options) {
		this.options = options;
	}
}
